import { createRouter, createWebHistory } from "vue-router";

// createRouter 创建路由实例
// 配置history模式
// createWebHashHistory 地址栏不带#号
// createWebHistory
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    { path: "/login", component: () => import("../views/login/Login.vue") },
    {
      path: "/",
      component: () => import("../views/main/Main.vue"),
      redirect: "/main/cart",
      children: [
        {
          path: "/main/home",
          component: () => import("../views/home/Home.vue"),
        },
        {
          path: "/main/product",
          component: () => import("../views/product/ProductDetail.vue"),
        },
        {
          path: "/main/cart",
          component: () => import("../views/cart/Cart.vue"),
        },
        {
          path: "/main/profile",
          component: () => import("../views/profile/Profile.vue"),
        },
      ],
    },
  ],
});

// vite 中的环境变量  import.meta.env.BASE_URL

// 路由守卫
router.beforeEach((to, from, next) => {
  const isLoggedIn = localStorage.getItem("isLoggedIn") === "true";

  if (to.meta.requiresAuth && !isLoggedIn) {
    next("/login");
  } else {
    next();
  }
});

export default router;
